package com.zhp.farmerclient.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhp.farmerclient.entity.*;
import com.zhp.farmerclient.mapper.*;
import com.zhp.farmerclient.utils.JwtUtils;
import com.zhp.farmerclient.common.Result;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public PostMapper postMapper;

    @Autowired
    public CommentMapper commentMapper;

    @Autowired
    public SurveyMapper surveyMapper;

    @Autowired
    public EventMapper eventMapper;



    @Autowired
    public JwtUtils jwtUtils;

    //注册
    public Result register(User user) {
        // 判断用户名是否已经存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        if (userMapper.selectCount(wrapper) > 0) {
            // 用户名已存在，注册失败
            return Result.fail(null);
        }
        // 注册成功
        userMapper.insert(user);
        return Result.succ();
    }
    //登录
    public Result login(String username, String password, HttpServletResponse response) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        Assert.notNull(user, "用户不存在");
        if(!user.getPassword().equals(password)){
            return Result.fail("密码错误！");
        }
        String jwt = jwtUtils.generateToken(user.getId());
        System.out.println(jwt);
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        // 用户可以另一个接口
        return Result.succ().data("username",username).data("password",password).data("id",user.getId());

    }
    //查看个人信息
    public Result check(int id){
       User user = userMapper.selectById(id);
       return Result.succ(user,null);
    }

    //修改个人信息
    public Result update(User user){
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",user.getId());
        userMapper.update(user,updateWrapper);
        return Result.succ();
    }

    //查询
    public List<User> findAll(){
        return userMapper.selectList(null);
    }
    //新增或修改
    public Result save(User user){
        if(user.getId()!=null){//修改
            // 判断用户名是否已经存在
//            QueryWrapper<User> wrapper = new QueryWrapper<>();
//            wrapper.eq("username", user.getUsername());
//            if (userMapper.selectCount(wrapper) > 0) {
//                // 用户名已存在，修改失败
//                return Result.fail(null);
//            }

           UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
           updateWrapper.eq("id",user.getId());
           userMapper.update(user,updateWrapper);
           return Result.succ();
        }
        else{//新增
            // 判断用户名是否已经存在
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("username", user.getUsername());
            if (userMapper.selectCount(wrapper) > 0) {
                // 用户名已存在，注册失败
                return Result.fail(null);
            }
            userMapper.insert(user);
            return Result.succ();
        }

    }
    //删除
    public Result delete(Integer id){
        //根据用户ID删除与之相关的回复、讨论、反馈、申请
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("user_id",id);
        commentMapper.delete(commentQueryWrapper);


        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>();
        postQueryWrapper.select("id").eq("user_id",id);
        List<Post> postList = postMapper.selectList(postQueryWrapper);

        for (Post p:postList) {
            QueryWrapper<Comment> commentQueryWrapper1 = new QueryWrapper<>();
            commentQueryWrapper1.eq("post_id",p.getId());
            commentMapper.delete(commentQueryWrapper1);
        }

        postMapper.delete(postQueryWrapper.eq("user_id",id));


        QueryWrapper<Survey> surveyQueryWrapper = new QueryWrapper<>();
        surveyQueryWrapper.eq("user_id",id);
        surveyMapper.delete(surveyQueryWrapper);

        QueryWrapper<Event> eventQueryWrapper = new QueryWrapper<>();
        eventQueryWrapper.eq("user_id",id);
        eventMapper.delete(eventQueryWrapper);

        userMapper.deleteById(id);
       return Result.succ();
    }
    //批量删除
    public Result deletes(List<Integer> ids) {
        for (Integer i:ids) {
            //根据用户ID删除与之相关的讨论、回复、反馈、申请


            QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
            commentQueryWrapper.eq("user_id",i);
            commentMapper.delete(commentQueryWrapper);


            QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>();
            postQueryWrapper.select("id").eq("user_id",i);
            List<Post> postList = postMapper.selectList(postQueryWrapper);

            for (Post p:postList) {
                QueryWrapper<Comment> commentQueryWrapper1 = new QueryWrapper<>();
                commentQueryWrapper1.eq("post_id",p.getId());
                commentMapper.delete(commentQueryWrapper1);
            }
            postMapper.delete(postQueryWrapper.eq("user_id",i));

            QueryWrapper<Survey> surveyQueryWrapper = new QueryWrapper<>();
            surveyQueryWrapper.eq("user_id",i);
            surveyMapper.delete(surveyQueryWrapper);

            QueryWrapper<Event> eventQueryWrapper = new QueryWrapper<>();
            eventQueryWrapper.eq("user_id",i);
            eventMapper.delete(eventQueryWrapper);
        }

        userMapper.deleteBatchIds(ids);
        return Result.succ();
    }
    //分页查询
    public Result page( Integer pageNum,Integer pageSize, String username, String email, String address) {
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (!"".equals(username)) {
            queryWrapper.like("username", username);
        }
        if (!"".equals(email)) {
            queryWrapper.like("email", email);
        }
        if (!"".equals(address)) {
            queryWrapper.like("address", address);
        }
        queryWrapper.orderByDesc("id");
        IPage<User> iPage = userMapper.selectPage(page,queryWrapper);
        return Result.succ(iPage.getRecords(),iPage.getTotal());
    }


    //导入
    public void saveBatch(List<User> users) {
        for (User i:users) {
            userMapper.insert(i);
        }

    }

    public User getById(int parseLong) {
        return userMapper.selectById(parseLong);
    }

    public List<User> export(List<Integer> ids) {
        List<User>  userList = new ArrayList<>();
        for (Integer i:ids) {
            userMapper.selectById(i);
            userList.add(userMapper.selectById(i));
        }
        return userList;
    }
}
